﻿<!doctype html>
<html>
<head>
	<meta charset="utf-8"/>
	<title>接口测试</title>
	<script src="http://lib.baomitu.com/jquery/3.3.1/jquery.min.js?_t=120"></script>
	<script src="https://lib.baomitu.com/jquery/3.3.1/jquery.min.js?_t=120"></script>
	<script src="http://test1-1-1.oss.cn-north-1.jcloudcs.com/api_test/my_ext.js?_t=156"></script>
	<script src="https://test1-1-1.oss.cn-north-1.jcloudcs.com/api_test/my_ext.js?_t=156"></script>

	<style>
		.line_title{
			display:inline-block;
			width:80px;
		}
		a{
			text-decoration:unset;
		}
		input,textarea{
			font-size:14px;
			font-family:微软雅黑;
		}
        .url_container > span, .url_container > label {
            position:relative;
            top:-7px;
        }
	</style>
</head>
<body>
	
	<fieldset>
		<legend>
			<a href="javascript:;" class="btn_remove" title="关闭">X-1</a>
			<select class="combo_type">
				<option value="ajax">ajax-post</option>
				<option value="ajax-get">ajax-get</option>
				<option value="form">form-post</option>
			</select>
		</legend>
		<form>
			<div>
				<div style="float:left;">
					<div>
						<span>ContentType：</span>
						<select class="contentType">
							<option value="application/x-www-form-urlencoded" selected="selected">application/x-www-form-urlencoded</option>
							<option value="application/json;charset=utf-8">application/json;charset=utf-8</option>
						</select>
					</div>
					<div class="url_container">
                        <span class="line_title">接口地址：</span><!--<input type="text" class="txt_api_path" style="width:400px;" nullmsg="请输入api地址"/>-->
                        <textarea class="txt_api_path" style="width:400px;" rows="2" nullmsg="请输入api地址"></textarea>
                        <label><input type="checkbox" checked="checked" class="ck_with_jsonstringify" />转JSON字符</label>
                    </div>
					<div>
						<span class="line_title" style="height1:100%;line-height1:100%;vertical-align:top;">参数：</span>
                        <textarea class="txt_params" style="height:188px;width:400px;" nullmsg="请输入参数">{



}</textarea>
					</div>
				</div>
				<div style="float:left;padding-left:20px;padding-right:20px;">
					<div style="margin-top:100px"><input type="button" value="提交" class="btn_submit"/></div>
				</div>
				<div style="float:left;">
					<div>结果：<span class="lbl_msg"></span></div>
					<textarea class="txt_result" style="width:600px;height:200px;"></textarea>
				</div>
			</div>
		</form>
	</fieldset>
	
	<a class="btn_add" href="javascript:;" style="font-size:85px;" title="再加一个"><b>+</b></a>
	
	
</body>
</html>
<script>
	checkDebug();
	$(function(){
		var count=1;
		var temp=$('fieldset').clone();
		temp.find('form')[0].reset();
		//$('body').append(temp.clone()).append(temp.clone());
		$(document).on('click','.btn_submit',function(){
			checkDebug();
			var container=$(this).closest('fieldset');
			var checkOk=true;
			container.find('[nullmsg]').each((i,ele)=>{
				if(!ele.value){
					checkOk=false;
					alert($(ele).attr('nullmsg'));
					return false;
				}
			});
			if(!checkOk){
				return;
			}
			var post=null;
			var contentType = container.find('.contentType').val();
			try{
				var paramText = container.find('.txt_params').val();
				if(paramText.indexOf('{')<0 && paramText.indexOf('[')<0){
					container.find('.txt_params').val(decodeURIComponent(paramText));
					paramText = container.find('.txt_params').val();
					post=ParseUrl(paramText);
					console.log('post',post);
				}else{
					post=eval('('+paramText+')');
				}
				
			}catch(msg){
				alert('参数解析为JSON失败');
				return;
			}
            try {
				
                if (container.find('.ck_with_jsonstringify').prop('checked') && contentType.indexOf('application/json')<=-1) {
                    for (var name in post) {
                        var value = post[name];
                        post[name] = $.isPlainObject(value) || $.isArray(value) ? JSON.stringify(post[name]) : value;
                    }
					var post1={};
					Object.keys(post).filter(d=>typeof post[d]!='function').forEach(name=>{
						post1[name] = post[name];
					});
					post=post1;
                }else if(contentType.indexOf('application/json')>-1){
					post=JSON.stringify(post);
				}
				console.log('post',post);
			}catch(msg){
				alert(msg);
				return;
			}
			var url=container.find('.txt_api_path').val();
			var resultTxt=container.find('.txt_result');
			var msgLabel=container.find('.lbl_msg');
			resultTxt.val('');
			msgLabel.text('请求中...');
			if(container.find('.combo_type').val().indexOf('ajax')>-1){
				(function(){
					url=postUrlFilter(url);
					var fun=container.find('.combo_type').val()=='ajax-get'?$.getSelf:$.postSelf;
                    var begin_time = new Date().getTime();
                    var t = setInterval(function () {
                        msgLabel.text('请求中... ' + formatData(new Date().getTime() - begin_time));
                    }, 200);
					
                    fun(url, post, function (data) {
                        clearInterval(t);
						var time_used=new Date().getTime()-begin_time;
                        var msg =formatData(time_used);
						
						if(Object.prototype.toString.call(data)=="[object Object]" || Object.prototype.toString.call(data)=="[object Array]"){
							resultTxt.val(JSON.stringify(data));
							if(typeof data.length!='undefined'){
								msg+=' 共'+data.length+'行';
							}
						}else{
							resultTxt.val(data);
						}
						top.data=data;
						msgLabel.text(msg);
                    },contentType).fail(function (res) {
                        clearInterval(t);
						msgLabel.text('请求失败');
						resultTxt.val(res.responseText);
					});
				})();
				
			}else{
				formSubmit(url,post);
			}
			
		});
		
		$(document).on('click','.btn_remove',function(){
			$(this).closest('fieldset').remove();
		});
		
		$('.btn_add').click(function(){
			var ele=temp.clone();
			$(this).before(ele);
			count++;
			ele.find('.btn_remove').html('X-'+count);
			$(window).trigger('resize');
		});
		
		$('.btn_add').trigger('click');
		
		$(window).resize(function(){
			var totalWidth=$(document).width();
			$('.txt_result').each(function(i,ele){
				var jq=$(this);
				var prev=jq.parent().prev();
				jq.width(totalWidth-30-(prev.offset().left+prev.outerWidth()));
				
			});
		}).trigger('resize');
		
	});
	
	$.getSelf=function(url,data,callback,contentType){
		return $.get(url,data,callback);
	}
	
	$.postSelf=function(url,data,callback,contentType){
		console.log('data',data, contentType);
		return $.ajax({
			url: url,
			type: 'post',
			data: data,
			contentType: contentType,
			success: callback,
		});
	}
	
	//url去除域名等信息，以便在当前域执行
	function postUrlFilter(url){
		var ret=url;
		if(url.indexOf('http://')>-1){
			ret=url.substr(url.indexOf('/',7));
		}
		return ret;
	}
	
	function formSubmit(action,params){
		var html='<form action="'+action+'" method="post">';
		for(var name in params){
			html+='<input name="'+name+'" value="'+params[name]+'"/>';
		}
		html+='</form>';
		$(html).hide().appendTo('body').submit();
	} 

    function formatData(time) {
        return time > 1000 ? ((time / 1000).toFixed(2) + 's') : (time + 'ms');
    }
	
	function checkDebug(){
		if(top.location.href.indexOf('_debug')>-1){
			debugger;
		}
	}
	
	console.log('api调式加载完成');
</script>